<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import { getCarbonStats,getRankList,getCarbonDistribution } from '@/api/Multifunction.js';
import { useUserStore } from '@/stores/user';
import dayjs from 'dayjs';

const userStore = useUserStore();
const userId = userStore.UserId;
const period = ref('today');
const carbonData = ref([]);
const xAxisData = ref([]);
const rankList = ref([]);
const carbonDistributionData = ref([]);



// 生成日期或时间范围的辅助函数
const generateDateRange = (startDate, endDate, unit) => {
  const dates = [];
  let current = dayjs(startDate);
  const lastDate = dayjs(endDate);

  if (unit === 'hour') {
    for (let i = 0; i < 24; i++) {
      dates.push(`${i}:00`);
    }
  } else if (unit === 'month') {
    for (let i = 1; i <= 12; i++) {
      dates.push(`${i}月`);
    }
  } else {
    while (current.isBefore(lastDate) || current.isSame(lastDate, unit)) {
      dates.push(current.format('YYYY-MM-DD'));
      current = current.add(1, unit);
    }
  }
  return dates;
};

// 初始化 ECharts 图表
const initChart = () => {
  const chartDom = document.getElementById('carbonChart');
  const myChart = echarts.init(chartDom);

  const option = {
    title: { text: '碳足迹统计' },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: xAxisData.value
    },
    yAxis: {
      type: 'value',
      name: 'kgCO₂', // 设置 Y 轴的单位名称
      nameTextStyle: {
        rich: {
          // 使用富文本设置 2 为下标
          value: {
            fontSize: 14,
          },
          sub: {
            fontSize: 10,
            verticalAlign: 'bottom'
          }
        },
        formatter: 'kgCO{sub|2}' // 通过富文本格式化
      }
    },
    series: [
      {
        data: carbonData.value,
        type: 'bar'
      }
    ]
  };

  myChart.setOption(option);
};


// 获取碳足迹数据
const fetchCarbonStats = async () => {
  const response = await getCarbonStats(userId, period.value);
  const {startDate, endDate, stats} = response.data.data;

  // 根据 period 生成完整的日期或时间范围
  const unit = period.value === 'year' ? 'month' : period.value === 'today' ? 'hour' : 'day';
  const allDates = generateDateRange(startDate, endDate, unit);

  // 根据 period 设置 statsMap 的 key 格式
  const statsMap = stats.reduce((map, item) => {
    const key = period.value === 'today' ? `${item.time}:00` : period.value === 'year' ? `${item.time}月` : item.time;
    map[key] = parseFloat(item.total.toFixed(2));
    return map;
  }, {});

  // 生成 xAxisData 和 carbonData，确保没有数据的时间 total 为 0
  xAxisData.value = allDates;
  carbonData.value = allDates.map(date => statsMap[date] !== undefined ? statsMap[date] : 0);

  initChart();
};
// 获取排行榜数据
const fetchRankList = async () => {
  const response = await getRankList();
  rankList.value = response.data.data;
};

const getAvatarBorderClass = (index) => {
  if (index === 0) return 'gold-border';
  if (index === 1) return 'silver-border';
  if (index === 2) return 'bronze-border';
  return '';
};
const getRankClass = (index) => {
  if (index === 0) return 'gold-trophy';
  if (index === 1) return 'silver-trophy';
  if (index === 2) return 'bronze-trophy';
  return '';
};

// 获取并处理碳排放分布数据
const fetchCarbonDistribution = async () => {
  const response = await getCarbonDistribution(userId);
  carbonDistributionData.value = response.data.data
      .filter(item => item.totalResult > 0) // 过滤掉负值
      .map(item => ({
        name: item.typeName,
        value: parseFloat(item.totalResult.toFixed(2)) // 保留两位小数
      }));
  initPieChart();
};

const initPieChart = () => {
  const chartDom = document.getElementById('carbonDistributionChart');
  const myChart = echarts.init(chartDom);

  const option = {
    title: {
      left: 'center',
      top: '5%',
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold',
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} kgCO₂ ({d}%)'

    },
    series: [
      {
        name: '碳排放',
        type: 'pie',
        radius: ['40%', '70%'], // 环形图样式
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside',
          formatter: '{b|{b}}\n{c|{c} kgCO₂}  {per|{d}%}', // 使用富文本
          rich: {
            b: {
              fontSize: 12,
              lineHeight: 25,
            },
            c: {
              fontSize: 12,
              fontWeight: 'bold',
              lineHeight: 25,
            },
            per: {
              color: '#fff',
              backgroundColor: '#334455',
              padding: [2, 4],
              borderRadius: 2
            }
          }
        },
        labelLine: {
          length: 20,
          length2: 15,
          smooth: true,
        },
        itemStyle: {
          borderRadius: 10, // 使扇区圆滑
          borderColor: '#fff',
          borderWidth: 2,
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.15)',
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 20,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        color: [
          {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#a6c1ff' },
              { offset: 1, color: '#5e5eff' }
            ]
          },
          {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#ff9a9e' },
              { offset: 1, color: '#fad0c4' }
            ]
          },
          {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#fbc2eb' },
              { offset: 1, color: '#a18cd1' }
            ]
          },
          // 其他渐变色
        ],
        data: carbonDistributionData.value
      }
    ]
  };

  myChart.setOption(option);
};







// 监控 period 变化
watch(period, fetchCarbonStats);

fetchCarbonStats();
fetchRankList();
fetchCarbonDistribution();

</script>

<template>
  <div style="display: flex;margin-left: 14%">
    <div>
      <!-- 时间切换按钮 -->
      <el-radio-group v-model="period" style="margin-top: 20px;">
        <el-radio-button label="today">今天</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="year">今年</el-radio-button>
      </el-radio-group>

      <!-- 碳足迹图表 -->
      <div id="carbonChart" style="width: 670px; height: 430px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);"></div>

    </div>

    <!-- 排行榜 -->
    <div style="margin-top: 70px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); width: 400px; height: 430px;margin-left: 40px;">
      <h3 style="text-align: center;">积分排行榜</h3>
      <el-scrollbar style="height: 350px;margin-left: 25px;">
        <ul style="font-weight: bold; font-size: 16px;">
          <li v-for="(user, index) in rankList" :key="user.nickname" :class="['rank-item', getRankClass(index)]" style="display: flex; align-items: center;">
            <img :src="user.avatar" alt="头像" class="avatar" :class="getAvatarBorderClass(index)" />
            <span style="margin-left: 10px;">{{ user.nickname }}</span> &nbsp&nbsp&nbsp&nbsp<span>{{ user.point }} 分</span>
            <div v-if="index === 0" class="gold-trophy" style="margin-left:12%;"><span style="font-size: 28px;">🥇 </span></div>
            <div v-else-if="index === 1" class="silver-trophy" style="margin-left:12%;"><span style="font-size: 28px;">🥈</span></div>
            <div v-else-if="index === 2" class="bronze-trophy" style="margin-left:12%;"> <span style="font-size: 28px;">🥉</span></div>
          </li>
        </ul>
      </el-scrollbar>
    </div>

  </div>
 <div>
   <div id="carbonDistributionChart" class="DistributionChart"></div>
   <span style="position: relative;top: -60px;right: -30%;font-size: 20px;color: #333;">我的碳排放分布</span>

 </div>
</template>



<style scoped>
#carbonChart {
  margin-top: 20px;
}
.rank-item {
  padding: 10px 0;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.gold-trophy {
  color: #cfaf03;

}
.silver-trophy {
  color: #a19e9e;
}
.bronze-trophy {
  color: #df842b; /* 铜色 */
}
.avatar.gold-border {
  border: 2px solid gold;
}
.avatar.silver-border {
  border: 2px solid silver;
}
.avatar.bronze-border {
  border: 2px solid #cd7f32; /* 铜色 */
}
.DistributionChart{
  width: 670px;
  height: 450px;
  margin-top: 50px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  margin-left: 14%;
}
</style>

